package cc.customer.phoneTask.services.Imp;

import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.phoneTask.dao.CPhoneTaskMapper;
import cc.customer.phoneTask.domain.CPhoneTask;
import cc.customer.phoneTask.services.CPhoneServices;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.MyUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class CPhoneServicesImp extends BaseService<CPhoneTask> implements CPhoneServices {

    private static final Logger logger = LoggerFactory.getLogger(CPhoneServicesImp.class);

    @Autowired
    private CPhoneTaskMapper cPhoneTaskMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public ResponseBo batchImpoertData(List<CPhoneTask> list) throws RuntimeException{
        try {
            List<CPhoneTask> all = new ArrayList<>();
            int numChongfu = 0;
            int num = 0;
            for (CPhoneTask task:list){
                //验证 手机号 是不是已经存在了
                CPhoneTask taskIshava = findCphoneTaskByMobile(task.getSpPhone());
                if (taskIshava == null){
                    all.add(task);
                    if(all.size()>300){
                        num += cPhoneTaskMapper.insertList(all);
                        all.clear();
                    }
                }else{
                    numChongfu++;
                }
            }
            if(!all.isEmpty()){
                num += cPhoneTaskMapper.insertList(all);
            }
            if (num >0){
                return ResponseBo.ok("导入成功数量:"+num+" 导入失败的数量: "+numChongfu);
            }
            return ResponseBo.error("导入成功数量:"+num+" 导入失败的数量: "+numChongfu);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("批量导入电话任务失败");
            throw new RuntimeException(e.getMessage());
        }
    }
    @Override
    public CPhoneTask findCphoneTaskByMobile(String Mobile) {
        Example example = new Example(CPhoneTask.class);
        example.createCriteria().andCondition("sp_phone=",Mobile);
        List<CPhoneTask> list = this.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }
    @Override
    public List<CPhoneTask> getAllCphoneTasks(CPhoneTask cPhoneTask) {
        try {
            List<CPhoneTask> list = cPhoneTaskMapper.selectAllPhoneTask(cPhoneTask);
            return list;
        }catch (Exception e){
            logger.error("获取电话任务失败:"+e.getMessage());
        }
        return new ArrayList<>();
    }
    @Override
    public List<CPhoneTask> getCphoneList(CPhoneTask cPhoneTask) {
        try {
            String spStatus = cPhoneTask.getSpStatus();
            Example example = new Example(CPhoneTask.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spUuid",cPhoneTask.getSpUuid());
            if (!StringUtils.isEmpty(spStatus)){
                if("9".equals(spStatus)){
                    /**未标记**/
                    criteria.andIsNull("spStatus");
                }else if ("10".equals(spStatus)){
                    /**已拨打**/
                    criteria.andIsNotNull("spLastRecord");
                }else if ("11".equals(spStatus)){
                    criteria.andIsNull("spLastRecord");
                }else{
                    criteria.andEqualTo("spStatus",spStatus);
                }
            }
            String start = cPhoneTask.getStarttime();
            String end = cPhoneTask.getEndtime();
            if (!StringUtils.isAnyEmpty(start,end)){
                criteria.andBetween("spCreatetime",start+" 00:00:00",end+" 23:59:59");
            }

            /**查询执行人**/
            String receve = cPhoneTask.getSpRecer();
            if (!StringUtils.isEmpty(receve)){
                criteria.andEqualTo("spRecer",receve);
            }
            List<CPhoneTask> list = this.selectByExample(example);
            for (CPhoneTask cPhoneTask1:list){
                if (!StringUtils.isEmpty(cPhoneTask1.getSpRecer())){
                    Example example1 = new Example(MyUser.class);
                    example1.createCriteria().andEqualTo("userUuid",cPhoneTask1.getSpRecer());
                    List<MyUser> lust = userMapper.selectByExample(example1);
                    MyUser user = lust.isEmpty() ? new MyUser() : lust.get(0);
                    cPhoneTask1.setSpFenName(user.getNickname());
                }
                if (!StringUtils.isEmpty(cPhoneTask1.getSpRecordUrl())){
                    String urlRecord = Constant.BIGEMP_FILE_RECORD_PATH+cPhoneTask1.getSpRecordUrl();
                    cPhoneTask1.setSpRecordUrl(urlRecord);
                }
                String time = cPhoneTask1.getSpLastRecord();
                if (!StringUtils.isEmpty(time)){
                    String datestr = DateUtil.getFormatDate(time,"yyyy-MM-dd");
                    cPhoneTask1.setSpLastRecord(datestr);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取到的电话任务失败:"+e.getMessage());
        }
        return new ArrayList<>();
    }

    @Override
    public ResponseBo selectStartis(String uuid) {
        try {
            CPhoneTask cPhoneTask = cPhoneTaskMapper.selectStartis(uuid);
            return ResponseBo.ok(cPhoneTask);
        }catch (Exception e){
            logger.error("获取统计数据失败:"+e.getMessage());
        }
        return ResponseBo.error();
    }

    @Override
    @Transactional
    public ResponseBo FenCphoneTasks(CPhoneTask cPhoneTask) throws Exception{
        try {
            String userids = cPhoneTask.getSpRecer();
            List<String> list = Arrays.asList(userids.split(","));
            String useridsnum = cPhoneTask.getSpFenName();
            List<String> num = Arrays.asList(useridsnum.split(","));

            Example example = new Example(CPhoneTask.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spUuid",cPhoneTask.getSpUuid());
            for (int i=0;i<list.size();i++){
                criteria.andIsNull("spRecer");
                List<CPhoneTask> allTask = this.selectByExample(example);
                int lastnum = Integer.valueOf(num.get(i));
                List<CPhoneTask> update = new ArrayList<>();
                if (allTask.size() >=lastnum){
                    update = allTask.subList(0,lastnum);
                }else{
                    update = allTask;
                }
                if (!update.isEmpty()){
                    List<String> uuids = new ArrayList<>();
                    for (CPhoneTask task :update){
                        uuids.add(task.getSpId()+"");
                    }
                    CPhoneTask cPhone = new CPhoneTask();
                    cPhone.setSpRecer(list.get(i));
                    cPhone.setSpStatusFen("2");
                    int numupdate = this.batchUpdate(uuids,"spId",CPhoneTask.class,cPhone);
                    logger.info("批次分配的数量: "+numupdate);
                }
            }
            return ResponseBo.ok();
        }catch (Exception e){
            logger.error("分配电话任务失败:"+e.getMessage());
            throw  new RuntimeException("分配电话任务失败:"+e.getMessage());
        }
    }
    @Override
    public ResponseBo selectSetInfo(String uuid) {
        try {
            List<CPhoneTask> cPhoneTasks = cPhoneTaskMapper.selectSetInfo(uuid);
            return ResponseBo.ok(cPhoneTasks);
        }catch (Exception e){
            logger.error("获取设置数据"+e.getMessage());
        }
        return ResponseBo.error();
    }

    @Override
    @Transactional
    public ResponseBo updateTaskRecer(CPhoneTask cPhoneTask) throws Exception {
        try {
            String yijiaoUser = cPhoneTask.getSpRecer();
            List<String> receUsers = Arrays.asList(yijiaoUser.split(","));
            String zhuanjiao = cPhoneTask.getSpFenName();
            List<String> zhuanjiaoUsers = Arrays.asList(zhuanjiao.split(","));

            Example example = new Example(CPhoneTask.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spUuid",cPhoneTask.getSpUuid());

            for (int i=0;i<receUsers.size();i++) {
                criteria.andEqualTo("spRecer",receUsers.get(i));
                List<CPhoneTask> allTask = this.selectByExample(example);
                String zhuan = zhuanjiaoUsers.get(i);
                List<String> listid = new ArrayList<>();
                for (CPhoneTask cPhone : allTask){
                    listid.add(cPhone.getSpId()+"");
                }
                CPhoneTask cPhone = new CPhoneTask();
                cPhone.setSpBatch(cPhoneTask.getSpBatch());
                cPhone.setSpRecer(zhuan);
                if (!allTask.isEmpty()){
                    this.batchUpdate(listid,"spId",CPhoneTask.class,cPhone);
                }
            }
        }catch (Exception e){
            throw new RuntimeException("转交客户失败:"+e.getMessage());
        }
        return ResponseBo.ok();
    }
    @Override
    public ResponseBo deleteTaskPhone(String uuid) {
        try {
            Example example = new Example(CPhoneTask.class);
            example.createCriteria().andEqualTo("spUuid",uuid);
            int num = this.cPhoneTaskMapper.deleteByExample(example);
            return num >0 ?ResponseBo.ok():ResponseBo.error();
        }catch (Exception e){
            logger.error("获取的电话任务删除"+e.getMessage());
        }
        return ResponseBo.error();
    }

    @Override
    @Transactional
    public ResponseBo updateTaskPhone(CPhoneTask cPhoneTask) throws Exception {
        try {
            int num = this.cPhoneTaskMapper.updateSelectOver(cPhoneTask.getSpUuid());
            logger.info(num+"");
            if (num >0) return ResponseBo.ok();
        }catch (Exception e){
            logger.error("移动到完成失败:"+e.getMessage());
            throw  new RuntimeException("移动到完成失败："+e.getMessage());
        }
        return ResponseBo.error();
    }

    @Override
    public ResponseBo updateTaskPhoneRecord(CPhoneTask cPhoneTask) {
        try {
            return this.updateNotNull(cPhoneTask) >0 ? ResponseBo.ok():ResponseBo.error();
        }catch (Exception e){
            logger.error("更改信息失败:"+e.getMessage());
        }
        return ResponseBo.error();
    }
}
